<template>
  <view class="p-12 bg-white page_min_height">
    <scroll-view class="whitespace-nowrap overflow-x-auto" :scroll-x="true" :enhanced="true" :show-scrollbar="false">
      <view
        v-for="item in categoryList"
        :key="item.id"
        class="px-18 py-6 mr-12 inline-block last:mr-0"
        :class="{ 'bg-blue-100 text-blue-500 rounded-full': item.id === pageParams.category_id }"
        @click="changeCategory(item.id)"
      >
        <text>{{ item.name }}</text>
      </view>
    </scroll-view>
    <DataLoading v-if="loading" />
    <template v-else>
      <view v-if="dataList.length" class="mt-12">
        <view v-for="item in dataList" :key="item.id" class="border-t border-solid border-gray-100">
          <ArticleItem :data="item" />
        </view>
      </view>
      <EmptyData v-else />
    </template>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onReachBottom } from '@dcloudio/uni-app';
import { getArticleCategoryApi, getArticleListApi } from '@/api/article';
import { usePage } from '@/utils/usePublic';
import ArticleItem from '@/components/ArticleItem.vue';

const loading = ref(true);
const pageParams = usePage({
  category_id: 0,
});
const categoryList = ref([{ id: 0, name: '全部' }]);

onLoad(async () => {
  getDataList();
  const { code, data } = await getArticleCategoryApi();
  if (code === 200) {
    categoryList.value = categoryList.value.concat(data.list);
  }
});

onReachBottom(() => {
  if (pageParams.isLoadAll) {
    return;
  }
  pageParams.page++;
  getDataList();
});

const dataList = ref([]);
// 获取文章列表
async function getDataList() {
  try {
    const { code, data } = await getArticleListApi(pageParams);
    loading.value = false;
    if (code === 200) {
      data.list.forEach(item => {
        item.contentTxt = item.content.replace(/<[^>]+>/g, '').substr(0, 30);
        item.cover = item.cover || '/static/images/default.png';
      });
      dataList.value = dataList.value.concat(data.list);
      pageParams.isLoadAll = data.list.length < pageParams.limit;
    }
  } catch (e) {
    loading.value = false;
    console.error(e);
  }
}
//  切换分类
function changeCategory(id) {
  loading.value = true;
  pageParams.category_id = id;
  pageParams.page = 1;
  dataList.value = [];
  getDataList();
}
</script>
